package com.l.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.l.demo.model.MyUserDo;
import com.l.demo.service.MyUserService;
import com.l.demo.mapper.MyUserMapper;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MyUserServiceImpl implements MyUserService{

    private final MyUserMapper myUserMapper;

    public MyUserServiceImpl(MyUserMapper myUserMapper) {
        this.myUserMapper = myUserMapper;
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 用户密码
     * @return 带id的用户信息
     */
    @Override
    public MyUserDo getUser(String username, String password) {
        MyUserDo userDo = myUserMapper.getUser(username, password);
        // 登录成功则更新登录时间
        if (userDo != null){
            myUserMapper.setLoginTime(userDo.getId());
        }
        return userDo;
    }

    /**
     * 用户是否存在
     * @param username
     * @return 存在则返回true, 不存在返回false
     */
    @Override
    public boolean isExist(String username) {
        return myUserMapper.exists(new LambdaQueryWrapper<MyUserDo>().eq(MyUserDo::getUsername, username));
    }

    /**
     * 用户注册
     * @param username
     * @param password
     * @return 带id的用户信息
     */
    @Override
    public MyUserDo registerUser(String username, String password) {
        // 转换成DO
        MyUserDo userDo = new MyUserDo();
        userDo.setUsername(username);
        userDo.setPassword(password);
        // 插入用户数据
        myUserMapper.insert(userDo);
        // 返回带id的用户数据
        return myUserMapper.getUser(username, password);
    }

    @Override
    public boolean logout(Integer id) {
        // 转换成DO
        MyUserDo userDo = new MyUserDo();
        userDo.setId(id);
        userDo.setLogoutTime(new Date());
        // 更新登出时间
        int row = myUserMapper.updateById(userDo);
        return row > 0;
    }
}




